import 'dart:io';
import 'package:yaml/yaml.dart';

void main(List<String> args) {
  try {
    // 解析命令行参数
    final platforms = _parsePlatformArgs(args);
    if (platforms.isEmpty) {
      print('Usage: dart sync_version.dart [-a] [-i] [-w]');
      print('Options:');
      print('  -a    Sync Android version');
      print('  -i    Sync iOS version');
      print('  -w    Sync Web version');
      print('If no options provided, syncs all platforms');
      return;
    }

    // 1. 从 pubspec.yaml 读取版本
    final versionInfo = _readPubspecVersion();
    print(
      'Current version: ${versionInfo.versionName}+${versionInfo.buildNumber}',
    );

    // 2. 根据参数更新指定平台
    if (platforms.contains('android') || platforms.isEmpty) {
      _updateAndroid(versionInfo.versionName, versionInfo.buildNumber);
      print('✅ Android version updated');
    }

    if (platforms.contains('ios') || platforms.isEmpty) {
      _updateIos(versionInfo.versionName, versionInfo.buildNumber);
      print('✅ iOS version updated');
    }

    if (platforms.contains('web') || platforms.isEmpty) {
      _updateWeb(versionInfo.versionName, versionInfo.buildNumber);
      print('✅ Web version updated');
    }
  } catch (e) {
    print('❌ Error: $e');
    exit(1);
  }
}

class VersionInfo {
  final String versionName;
  final String buildNumber;

  VersionInfo(this.versionName, this.buildNumber);
}

List<String> _parsePlatformArgs(List<String> args) {
  final platforms = <String>[];
  for (final arg in args) {
    switch (arg) {
      case '-a':
        platforms.add('android');
        break;
      case '-i':
        platforms.add('ios');
        break;
      case '-w':
        platforms.add('web');
        break;
    }
  }
  return platforms;
}

VersionInfo _readPubspecVersion() {
  final file = File('pubspec.yaml');
  if (!file.existsSync()) {
    throw Exception('pubspec.yaml not found');
  }

  final pubspec = loadYaml(file.readAsStringSync());
  final version = pubspec['version']?.toString();
  if (version == null) {
    throw Exception('No version found in pubspec.yaml');
  }

  final parts = version.split('+');
  if (parts.length != 2) {
    throw Exception(
      'Invalid version format, expected: MAJOR.MINOR.PATCH+BUILD',
    );
  }

  return VersionInfo(parts[0], parts[1]);
}

void _updateAndroid(String versionName, String buildNumber) {
  final file = File('android/app/build.gradle');
  if (!file.existsSync()) {
    throw Exception('Android build.gradle not found');
  }

  final content = file
      .readAsStringSync()
      .replaceAllMapped(
        RegExp(r'versionName\s+".*"'),
        (match) => 'versionName "$versionName"',
      )
      .replaceAllMapped(
        RegExp(r'versionCode\s+\d+'),
        (match) => 'versionCode ${int.parse(buildNumber)}',
      );

  file.writeAsStringSync(content);
}

void _updateIos(String versionName, String buildNumber) {
  final file = File('ios/Runner/Info.plist');
  if (!file.existsSync()) {
    throw Exception('iOS Info.plist not found');
  }

  final content = file
      .readAsStringSync()
      .replaceAllMapped(
        RegExp(r'<key>CFBundleShortVersionString</key>\s*<string>.*</string>'),
        (match) =>
            '<key>CFBundleShortVersionString</key>\n\t<string>$versionName</string>',
      )
      .replaceAllMapped(
        RegExp(r'<key>CFBundleVersion</key>\s*<string>.*</string>'),
        (match) =>
            '<key>CFBundleVersion</key>\n\t<string>$buildNumber</string>',
      );

  file.writeAsStringSync(content);
}

void _updateWeb(String versionName, String buildNumber) {
  final file = File('web/index.html');
  if (!file.existsSync()) {
    throw Exception('web/index.html not found');
  }

  final content = file
      .readAsStringSync()
      .replaceAll('%VERSION%', versionName)
      .replaceAll('%BUILD_NUMBER%', buildNumber);

  file.writeAsStringSync(content);
}
